﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Web;
using MDF.Logger.Managements;
using MDF.Utilites.Helper;

namespace MDF.Requesting
{
    public class Requester
    {
        private CookieContainer m_ccCookie = new CookieContainer();
        private int m_iRepeat =2;
        private string m_strCookie = null;
        public string Cookie
        {
            set
            {
                m_strCookie = value;
                m_ccCookie = new CookieContainer();
            }
        }
        public WebResponse GetData(String _strURL, bool _isUseProxy = false, CookieContainer _ccCookie = null)
        {
            DateTime dtStart = DateTime.Now;
            WebResponse res = null;
            for (int i = 0; i < m_iRepeat; i++)
            {
                var uri = new Uri(_strURL);
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
                request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:5.0) Gecko/20100101 Firefox/5.0";
                request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
                request.Headers.Add("Accept-Language", "en-us,en;q=0.5");
                request.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
                if (_ccCookie != null)
                    request.CookieContainer = _ccCookie;
                else
                    request.CookieContainer = m_ccCookie;
                if (m_strCookie != null)
                {
                    m_strCookie=m_strCookie.Replace(';',',');
                    m_ccCookie.SetCookies(uri, m_strCookie);
                    m_strCookie = null;
                    LogManager.GetInstance().Info("Set cookie: " + _strURL);
                }
                if (_isUseProxy)
                    request.Proxy = new WebProxy("186.235.237.58", 8080);
                request.KeepAlive = true;
                request.Referer = _strURL;

                request.ContentType = "application/x-www-form-urlencoded";
                request.Headers.Add("Cache-Control", "max-age");
                request.Headers.Add("Origin", _strURL);
                request.Method = "GET";
                //request.Timeout = 15000;
                try
                {
                    res = request.GetResponse();
                    if (res.Headers["Set-Cookie"] != null)
                    {
                        try
                        {
                            var coki = res.Headers["Set-Cookie"].Replace(';', ',');
                            m_ccCookie.SetCookies(uri, coki);
                        }
                        catch(Exception ex)
                        {
                            //LogManager.GetInstance().Error("Cant setcookie for "+_strURL);
                        }
                        DateTime dtEnd = DateTime.Now;
                        var time = dtEnd.Subtract(dtStart);
                        string strLoading = "";
                        for (int j = 0; j < (int)time.TotalSeconds; j++)
                        {
                            strLoading += ".";
                        }
                        LogManager.GetInstance().Info(string.Format("GET {2}: {0}({1})", _strURL, (int)time.TotalSeconds, strLoading));
                    }
                    if (res != null)
                        return res;
                    else
                    {
                        LogManager.GetInstance().Warning("Get again " + i + ": " + _strURL);
                    }
                }
                catch (Exception ex)
                {
                    LogManager.GetInstance().Error(_strURL+" Get respone Get data have a problem!", ex);
                    LogManager.GetInstance().Warning("Get again " + (i + 1) + ": " + _strURL);
                }
            }
            return res;
        }

        //hàm post
        public WebResponse PostData(String _strURL, String _strData, bool _isUseProxy = false, CookieContainer _ccCookie = null)
        {
            return this.PostDataFrom(_strURL, _strURL, _strData, _isUseProxy, _ccCookie);
        }

        public WebResponse PostDataFrom(String _strURL,string _strRef, String _strData, bool _isUseProxy = false, CookieContainer _ccCookie = null)
        {
            WebResponse res = null;
            for (int i = 0; i < m_iRepeat; i++)
            {
                DateTime dtStart = DateTime.Now;
                var uri = new Uri(_strURL);
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
                byte[] data = Encoding.UTF8.GetBytes(_strData);//builder.ToString());

                request.UserAgent = "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.114 Safari/537.36";

                request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";

                request.Headers.Add("Accept-Language", "en-us,en;q=0.5");

                request.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3");

                request.KeepAlive = true;
                if (_isUseProxy)
                    request.Proxy = new WebProxy("186.235.237.58", 8080);
                if (_ccCookie != null)
                    request.CookieContainer = _ccCookie;
                else
                    request.CookieContainer = m_ccCookie;
                if (m_strCookie != null)
                {
                    m_strCookie = m_strCookie.Replace(';', ',');
                    m_ccCookie.SetCookies(uri, m_strCookie);
                    m_strCookie = null;
                    //LogManager.GetInstance().Info("Set cookie: " + _strURL);
                }
                request.ContentType = "application/x-www-form-urlencoded";
                request.Referer = _strRef;
                request.Headers.Add("Cache-Control", "max-age");
                request.ContentLength = data.Length;
                //request.Timeout = 15000;
                request.Method = "POST";

                try
                {
                    //thuong xay ra loi tai day (-_-)
                    Stream stream = request.GetRequestStream();
                    stream.Write(data, 0, data.Length);
                    stream.Close();
                }
                catch (Exception ex)
                {
                    LogManager.GetInstance().Error(_strURL + " Send post data request have a problem!", ex);
                    LogManager.GetInstance().Warning("Get again " + (i + 1) + ": " + _strURL);
                }
                try
                {
                    res = request.GetResponse();
                    try
                    {
                        var coki = res.Headers["Set-Cookie"].Replace(';', ',');
                        m_ccCookie.SetCookies(uri, coki);
                    }
                    catch (Exception ex)
                    {
                        //LogManager.GetInstance().Error("Cant setcookie for " + _strURL);
                    }
                    DateTime dtEnd = DateTime.Now;
                    var time = dtEnd.Subtract(dtStart);
                    string strLoading = "";
                    for (int j = 0; j < (int)time.TotalSeconds; j++)
                    {
                        strLoading += ".";
                    }
                    LogManager.GetInstance().Info(string.Format("POST {2}: {0}({1})", _strURL, (int)time.TotalSeconds, strLoading));
                    if (res != null)
                        return res;
                }
                catch (Exception ex)
                {
                    LogManager.GetInstance().Error(_strURL + " Get respones Post data have a problem!", ex);
                    LogManager.GetInstance().Warning("Get again " + (i + 1) + ": " + _strURL);
                }
            }
            return res;
        }


        //tra ve ma html tu response
        public String GetHtmlFromResponse(WebResponse response)
        {
            if (response == null)
            {
                LogManager.GetInstance().Error("WebResponse is null");
                return null;
            }
            string temp = "";
            try
            {
                using (StreamReader sr = new StreamReader(response.GetResponseStream()))
                {
                    temp = sr.ReadToEnd();
                    //Close and clean up the StreamReader
                    sr.Close();
                }
            }
            catch (Exception ex)
            {
                LogManager.GetInstance().Error("Get HTML have a problem!", ex);
                return "";
            }
            finally
            {
                response.Close();
            }
            return temp;
        }
    }
}